<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2019-05-24
 * Time: 11:51
 */
namespace frontend\modules\Api\controllers;

use common\event\TallyEvent;
use common\models\TallyPm;
use common\models\User;
use common\services\TallyPmService;
use common\services\UserService;
use Yii;
use frontend\controllers\RestController;
use yii\helpers\ArrayHelper;

/**
 * Class ApiController
 * @package frontend\modules\Api\controllers
 */
class ApiController extends RestController
{
    /**
     * @var bool
     * 禁用CSRF校验
     */
    public $enableCsrfValidation = false;

    /**
     * @var
     * 用户信息
     */
    public $_user ;

    /**
     * @var $token string 用户登录标识
     */
    public $token ;

    /**
     * 初始化方法
     * @throws
     */
    public function init()
    {
        parent::init();
        // 禁用session登录
        Yii::$app->user->enableSession = false;
        // 获取header头部的token
        $loginToken     = Yii::$app->request->headers->get('token');
        $this->token    = $loginToken ;
        $identity       = User::findIdentityByAccessToken($loginToken);
        if($identity){
            // 登录成功设置用户信息
            Yii::$app->user->setIdentity($identity);
            $this->_user = ArrayHelper::toArray(Yii::$app->user->identity);
            // 随机延续登录状态有效期
            if( rand(1, 10) == 1) {
                UserService::storeLoginToken($loginToken,$this->_user['id']);
            }
        }
    }

    /**
     * @param $data array 日志数据
     * 触发相关事件
     */
    protected function triggerEvents($data)
    {
        // 触发日志记录事件
        $e = new TallyEvent([
            'logData' => $data
        ]);
        $this->trigger(TallyEvent::RECORD_LOG_EVENT,$e);
    }

    /**
     * 检查是否具备数据操作权限
     * @param        $uid
     * @param        $tallyId
     * @param string $permission enum read|write|audit
     *
     * @throws \yii\base\ExitException
     * @return mixed
     */
    public function checkRolePermission($uid,$tallyId,$permission='read')
    {
        if(!TallyPmService::checkPermission($uid,$tallyId,$permission)){
            return self::failureResponse(500,'抱歉，无操作权限');
        }
        return true;
    }

    /**
     * 判断用户对账套的角色是否为管理员
     * @param $uid
     * @param $tallyId
     *
     * @return bool
     */
    public function isAdminRole($uid,$tallyId)
    {
        $role = TallyPmService::getRole($uid,$tallyId);
        return $role == TallyPm::ROLE_ADMIN ;
    }




    /**
     * desc:检测数据
     * admin
     * email:
     * @param array $params
     * @param string $field
     * @return bool
     */
    function checkIsHasField($params = [],$field = ''){
        return isset($params[$field]) && $params[$field] !== '' && !is_null($params[$field]);
    }
}
